{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "82a2cd0a-5510-4fa4-8ca7-9308f3de978b",
   "metadata": {},
   "source": [
    "# Python文件与目录操作\r\n",
    "\r\n",
    "### 1. 文件打开与关闭\r\n",
    "\r\n",
    "- 使用`open()`函数可以打开一个文件，并返回一个文件对象。`open()`函数的第一个参数是文件的路径，第二个参数是模式，下面详细解释`open()`函数的各种模式：\r\n",
    "\r\n",
    "  ###### 基本模式\r\n",
    "\r\n",
    "  - **`'r'`**: 读模式（默认）。如果文件不存在，会抛出一个`FileNotFoundError`错误。\r\n",
    "  - **`'w'`**: 写模式。如果文件已存在，会被覆盖；如果文件不存在，会创建一个新文件。\r\n",
    "  - **`'a'`**: 追加模式。如果文件已存在，新写入的数据会被追加到文件末尾；如果文件不存在，会创建一个新文件进行写入。\r\n",
    "  - **`'x'`**: 独占创建模式。如果文件已存在，操作会失败；只有当文件不存在时，才创建新文件进行写入。这个模式用于创建一个新文件，如果文件名已存在，会抛出一个`FileExistsError`错误。\r\n",
    "\r\n",
    "  ###### 扩展模式\r\n",
    "\r\n",
    "  - **`'b'`**: 二进制模式。与上述模式结合使用（如`'rb'`、`'wb'`、`'ab'`），用于二进制文件的读写。\r\n",
    "  - **`'t'`**: 文本模式（默认）。与上述模式结合使用（如`'rt'`、`'wt'`、`'at'`），用于文本文件的读写。这是默认模式，通常可以省略不写。\r\n",
    "  - **`'+'`**: 更新模式，用于读写。与上述模式结合使用（如`'r+'`、`'w+'`、`'a+'`），可以同时进行读写操作。\r\n",
    "\r\n",
    "  ###### 模式组合示例\r\n",
    "\r\n",
    "  - **`'rb'`\\**或\\**`'wb'`\\**或\\**`'ab'`**: 分别代表二进制读模式、二进制写模式、二进制追加模式。用于处理非文本文件，如图片、视频等。\r\n",
    "  - **`'r+'`**: 读写模式。文件必须已存在，允许读取文件内容，也可以写入新内容，写入的内容会覆盖原有内容。\r\n",
    "  - **`'w+'`**: 写读模式。如果文件存在，会被覆盖；如果不存在，会创建新文件。允许写入新内容，也可以读取写入的内容。\r\n",
    "  - **`'a+'`**: 追加读写模式。如果文件存在，写入的新内容会被追加到文件末尾；如果文件不存在，会创建新文件。允许读取文件内容和写入新内容。\r\n",
    "\r\n",
    "  使用这些模式时，需要根据实际需求选择最合适的模式。例如，如果需要处理二进制文件，就应该使用带`'b'`的模式；如果是读取文本文件，通常使用默认的文本模式（`'r'`或`'rt'`）；如果需要在打开文件后执行读写操作，可以选择`'+'`更新模式的组合形式。\r\n",
    "\r\n",
    "- 打开文件后，应当使用`close()`方法来关闭文件，这是因为文件资源是有限的系统资源，及时关闭未使用的文件可以回收资源，防止资源泄露，并确保数据被正确写入文件。\r\n",
    "\r\n",
    "第三个参数encoding就是编码格式，一般为utf-8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "276888a6-d5a3-4c0e-8ad8-662394c09a78",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First line.\n",
      "Second line.\n",
      "\n",
      "First line.\n",
      "Second line.\n",
      "First line.\n",
      "Second line.\n"
     ]
    }
   ],
   "source": [
    "# 使用read()读取全部内容，并指定编码为UTF-8\n",
    "with open('example.txt', 'r', encoding='utf-8') as file:\n",
    "    print(file.read())\n",
    "\n",
    "# 使用readline()逐行读取，并指定编码为UTF-8\n",
    "with open('example.txt', 'r', encoding='utf-8') as file:\n",
    "    line = file.readline()\n",
    "    while line:\n",
    "        print(line, end='')  # print自带换行，end=''避免重复换行\n",
    "        line = file.readline()\n",
    "\n",
    "# 使用readlines()获取所有行，并指定编码为UTF-8\n",
    "with open('example.txt', 'r', encoding='utf-8') as file:\n",
    "    for line in file.readlines():\n",
    "        print(line, end='')\n",
    "\n",
    "# 使用write()写入字符串，并指定编码为UTF-8\n",
    "with open('example.txt', 'w', encoding='utf-8') as file:\n",
    "    file.write('One line.\\n')\n",
    "\n",
    "# 使用writelines()写入多行，并指定编码为UTF-8\n",
    "lines = ['First line.\\n', 'Second line.\\n']\n",
    "with open('example.txt', 'w', encoding='utf-8') as file:\n",
    "    file.writelines(lines)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4882eb6-460c-4247-a1d6-55fee0f90606",
   "metadata": {},
   "source": [
    "### 2.文件读取与写入详解\n",
    "\n",
    "在Python中，文件对象提供了多个方法来进行文件的读取和写入操作，每种方法适用于不同的场景。\n",
    "\n",
    "使用`with`语句以读取模式打开一个名为`'example.txt'`的文件，假设这个文件使用了某种“原始编码”保存。`with`语句确保文件在代码块执行完毕后被自动关闭。在`with`语句的代码块内，文件对象被赋值给变量`file`，你可以通过`file`来执行文件读取操作。\n",
    "\n",
    "#### 1. `read()` 方法\n",
    "\n",
    "- **作用**：`read(size=-1)` 方法一次性读取并返回文件的全部内容，或者在给定`size`参数的情况下返回指定字节数的内容。\n",
    "- **参数**：`size`是一个可选参数，指定要读取的字符数（文本模式）或字节数（二进制模式）。如果省略或为负数，则读取并返回整个文件内容。\n",
    "\n",
    "#### 2. `readline()` 方法\n",
    "\n",
    "- **作用**：`readline(size=-1)` 每次调用读取文件的下一行。\n",
    "- **参数**：`size`是一个可选参数，表示从行中读取的最大字符数（包括行结束符）。如果省略或为负数，则读取整行。\n",
    "\n",
    "#### 3. `readlines()` 方法\n",
    "\n",
    "- **作用**：`readlines(hint=-1)` 读取文件的所有行并以列表形式返回。\n",
    "- **参数**：`hint`是一个可选参数，指定要读取的行的大致总字节数。实际读取的行数可能多或少，具体取决于文件内容。\n",
    "\n",
    "#### 4. `write()` 方法\n",
    "\n",
    "- **作用**：`write(s)` 方法将字符串`s`写入文件。\n",
    "- **参数**：`s`必须是一个字符串（文本模式）或字节序列（二进制模式）。\n",
    "\n",
    "#### 5. `writelines()` 方法\n",
    "\n",
    "- **作用**：`writelines(lines)` 方法用于将一个字符串列表写入文件。\n",
    "- **参数**：`lines`是一个字符串列表，列表中的每个字符串将按顺序写入文件。注意，`writelines()`不会自动添加行结束符。\n",
    "\n",
    "### 代码示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "d996d020-8312-4643-856c-c82be947fabd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First line.\n",
      "Second line.\n",
      "\n",
      "First line.\n",
      "Second line.\n",
      "First line.\n",
      "Second line.\n"
     ]
    }
   ],
   "source": [
    "# 使用read()读取文件的全部内容\n",
    "with open('example.txt', 'r', encoding='utf-8') as file:\n",
    "    content = file.read()\n",
    "    print(content)  # 打印文件内容\n",
    "\n",
    "# 使用readline()逐行读取\n",
    "with open('example.txt', 'r', encoding='utf-8') as file:\n",
    "    line = file.readline()\n",
    "    while line:\n",
    "        print(line, end='')  # 逐行打印，end=''避免额外换行\n",
    "        line = file.readline()\n",
    "\n",
    "# 使用readlines()获取所有行，并打印\n",
    "with open('example.txt', 'r', encoding='utf-8') as file:\n",
    "    lines = file.readlines()\n",
    "    for line in lines:\n",
    "        print(line, end='')  # 打印每一行\n",
    "\n",
    "# 使用write()向文件写入一个字符串\n",
    "with open('example.txt', 'w', encoding='utf-8') as file:\n",
    "    file.write('这是一个测试字符串。\\n')\n",
    "\n",
    "# 使用writelines()写入多行\n",
    "lines = ['第一行内容\\n', '第二行内容\\n']\n",
    "with open('example.txt', 'w', encoding='utf-8') as file:\n",
    "    file.writelines(lines)  # 写入多行内容\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce417cea-3f29-46b4-9b0c-4543104cc802",
   "metadata": {},
   "source": [
    "### 3. 文件定位读写\n",
    "\n",
    "#### 讲解:\n",
    "\n",
    "- `tell()`方法返回文件指针当前所在的位置，它是从文件开头计算的字节数（在二进制模式下）或字符数（在文本模式下）。\n",
    "- `seek(offset, whence=0)`方法用于移动文件读写指针到指定位置。`offset`表示相对于`whence`的位置：如果`whence`为0（默认值），则从文件开头计算；如果为1，从当前位置计算；如果为2，从文件末尾计算。通常，`seek(0)`用于移动到文件开头。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "00206a5c-204e-4d13-9081-e4bb83cb9b6c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前位置: 29\n",
      "回到位置: 0\n",
      "文件开始处的内容。\n",
      "容\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 使用'r+'模式同时进行读写操作，并指定编码为UTF-8\n",
    "with open('example.txt', 'r+', encoding='utf-8') as file:\n",
    "    file.write('文件开始处的内容。\\n')  # 写入内容\n",
    "    print('当前位置:', file.tell())  # 显示当前指针位置\n",
    "    # 回到文件开头\n",
    "    file.seek(0)\n",
    "    print('回到位置:', file.tell())  # 显示当前指针位置\n",
    "    print(file.read())  # 读取并打印文件内容\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f81c953-d39f-418c-abeb-3177f1d9312a",
   "metadata": {},
   "source": [
    "### 4. 文件与目录重命名\n",
    "\n",
    "- `os.rename(src, dst)`函数用于重命名文件或目录，`src`是原始名称，`dst`是新名称。\n",
    "\n",
    "#### 代码示例:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3fdcea19-47bb-4e05-940b-e2d01960d4fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# 重命名文件从'old_name.txt'到'new_name.txt'\n",
    "os.rename('old_name.txt', 'new_name.txt')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdc05374-6dba-45f4-ab88-fa5022f2b715",
   "metadata": {},
   "source": [
    "### 5. 获取目录文件列表\n",
    "\n",
    "- `os.listdir(path='.')`函数返回指定目录下的文件和目录列表。默认为当前目录。\n",
    "- `Path.iterdir()`方法返回一个迭代器，包含目录中所有文件和子目录的`Path`对象。\n",
    "\n",
    "#### 代码示例:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c50f4b9f-fc12-4294-a3b8-32b09f2de217",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[' Python文件与目录操作.ipynb', '.git', '.idea', '.ipynb_checkpoints', 'AdobeHeitiStd-Regular.otf', 'example.txt', 'hello.py', 'main.py', 'math_operations.py', 'math_utils.py', 'my_math_package', 'new_name.txt', 'Python函数.ipynb', 'Python模块.ipynb', 'Python的基础语法.ipynb', 'Untitled.ipynb', 'Untitled1.ipynb', 'wukong.png', 'xiyou.jpg', 'xiyou1`.jpg', 'xiyouji.txt', '__pycache__', '初识Python.ipynb', '字符串.ipynb', '流程控制.ipynb', '环境配置.md', '邂逅python.ipynb', '面向对象编程.ipynb']\n",
      " Python文件与目录操作.ipynb\n",
      ".git\n",
      ".idea\n",
      ".ipynb_checkpoints\n",
      "AdobeHeitiStd-Regular.otf\n",
      "example.txt\n",
      "hello.py\n",
      "main.py\n",
      "math_operations.py\n",
      "math_utils.py\n",
      "my_math_package\n",
      "new_name.txt\n",
      "Python函数.ipynb\n",
      "Python模块.ipynb\n",
      "Python的基础语法.ipynb\n",
      "Untitled.ipynb\n",
      "Untitled1.ipynb\n",
      "wukong.png\n",
      "xiyou.jpg\n",
      "xiyou1`.jpg\n",
      "xiyouji.txt\n",
      "__pycache__\n",
      "初识Python.ipynb\n",
      "字符串.ipynb\n",
      "流程控制.ipynb\n",
      "环境配置.md\n",
      "邂逅python.ipynb\n",
      "面向对象编程.ipynb\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "# 显示当前目录下的所有文件和目录\n",
    "print(os.listdir('.'))\n",
    "\n",
    "# 使用pathlib显示当前目录下的所有文件和目录\n",
    "path = Path('.')\n",
    "for entry in path.iterdir():\n",
    "    print(entry)\n",
    "    # print(type(entry))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "070471b7-24aa-4b3e-ad26-f9870f3b2af8",
   "metadata": {},
   "source": [
    "### 6. 文件删除\n",
    "\n",
    "- `os.remove(path)`用于删除一个文件。\n",
    "- `Path.unlink()`方法作用相同，删除一个文件。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "a80d45e4-a62b-4345-89a8-0d4c3ce5b9c7",
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[WinError 2] 系统找不到指定的文件。: 'file_to_delete.txt'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[17], line 5\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mpathlib\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m Path\n\u001b[0;32m      4\u001b[0m \u001b[38;5;66;03m# 删除一个名为'file_to_delete.txt'的文件\u001b[39;00m\n\u001b[1;32m----> 5\u001b[0m \u001b[43mos\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mremove\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mfile_to_delete.txt\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[0;32m      7\u001b[0m \u001b[38;5;66;03m# 使用pathlib删除文件\u001b[39;00m\n\u001b[0;32m      8\u001b[0m Path(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mfile_to_delete.txt\u001b[39m\u001b[38;5;124m'\u001b[39m)\u001b[38;5;241m.\u001b[39munlink()\n",
      "\u001b[1;31mFileNotFoundError\u001b[0m: [WinError 2] 系统找不到指定的文件。: 'file_to_delete.txt'"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "# 删除一个名为'file_to_delete.txt'的文件\n",
    "os.remove('file_to_delete.txt')\n",
    "\n",
    "# 使用pathlib删除文件\n",
    "Path('file_to_delete.txt').unlink()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c3d5938-2630-46b3-9e29-aac77b05d2f6",
   "metadata": {},
   "source": [
    "### 7. 创建目录\n",
    "\n",
    "- `os.mkdir(path)`用于创建一个新目录。\n",
    "- `Path.mkdir()`方法相同作用，创建一个新目录。\n",
    "\n",
    "#### 代码示例:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "749f6214-c564-476a-bc7a-dcb05549ad7c",
   "metadata": {},
   "outputs": [
    {
     "ename": "FileExistsError",
     "evalue": "[WinError 183] 当文件已存在时，无法创建该文件。: 'new_directory'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mFileExistsError\u001b[0m                           Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[19], line 8\u001b[0m\n\u001b[0;32m      5\u001b[0m os\u001b[38;5;241m.\u001b[39mmkdir(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mnew_directory\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[0;32m      7\u001b[0m \u001b[38;5;66;03m# 使用pathlib创建目录\u001b[39;00m\n\u001b[1;32m----> 8\u001b[0m \u001b[43mPath\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mnew_directory\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmkdir\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[1;32m~\\MiniConda3\\lib\\pathlib.py:1175\u001b[0m, in \u001b[0;36mPath.mkdir\u001b[1;34m(self, mode, parents, exist_ok)\u001b[0m\n\u001b[0;32m   1171\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m   1172\u001b[0m \u001b[38;5;124;03mCreate a new directory at this given path.\u001b[39;00m\n\u001b[0;32m   1173\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m   1174\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m-> 1175\u001b[0m     \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_accessor\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmkdir\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mmode\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m   1176\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mFileNotFoundError\u001b[39;00m:\n\u001b[0;32m   1177\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m parents \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mparent \u001b[38;5;241m==\u001b[39m \u001b[38;5;28mself\u001b[39m:\n",
      "\u001b[1;31mFileExistsError\u001b[0m: [WinError 183] 当文件已存在时，无法创建该文件。: 'new_directory'"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "# 创建一个名为'new_directory'的新目录\n",
    "os.mkdir('new_directory')\n",
    "\n",
    "# 使用pathlib创建目录\n",
    "Path('new_directory').mkdir()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee51ed5b-c410-4542-bc3f-ee48118ae242",
   "metadata": {},
   "source": [
    "### 8. 删除目录\n",
    "\n",
    "- `os.rmdir(path)`用于删除空目录。\n",
    "- `Path.rmdir()`方法同样用于删除空目录。\n",
    "- `shutil.rmtree(path)`用于删除非空目录及其所有内容。\n",
    "\n",
    "#### 代码示例:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "8320cd61-5a63-4a42-a6ac-2e770e410f22",
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[WinError 2] 系统找不到指定的文件。: 'empty_directory'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[21], line 6\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mshutil\u001b[39;00m\n\u001b[0;32m      5\u001b[0m \u001b[38;5;66;03m# 删除一个空目录'empty_directory'\u001b[39;00m\n\u001b[1;32m----> 6\u001b[0m \u001b[43mos\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrmdir\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mempty_directory\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[0;32m      8\u001b[0m \u001b[38;5;66;03m# 使用pathlib删除一个空目录\u001b[39;00m\n\u001b[0;32m      9\u001b[0m Path(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mempty_directory\u001b[39m\u001b[38;5;124m'\u001b[39m)\u001b[38;5;241m.\u001b[39mrmdir()\n",
      "\u001b[1;31mFileNotFoundError\u001b[0m: [WinError 2] 系统找不到指定的文件。: 'empty_directory'"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "import shutil\n",
    "\n",
    "# 删除一个空目录'empty_directory'\n",
    "os.rmdir('empty_directory')\n",
    "\n",
    "# 使用pathlib删除一个空目录\n",
    "Path('empty_directory').rmdir()\n",
    "\n",
    "# 删除一个非空目录'non_empty_directory'及其所有内容\n",
    "shutil.rmtree('non_empty_directory')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf5af4b2-f4a1-47c5-bf4a-70060ba34af5",
   "metadata": {},
   "source": [
    "### 9. 更改当前工作目录\n",
    "\n",
    "- `os.chdir(path)`函数用于改变当前工作目录到指定的路径。\n",
    "\n",
    "#### 代码示例:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "1c2109ee-387b-4aac-85e1-0d527dad6975",
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[WinError 3] 系统找不到指定的路径。: '/path/to/directory'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[22], line 4\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mos\u001b[39;00m\n\u001b[0;32m      3\u001b[0m \u001b[38;5;66;03m# 更改当前工作目录到'/path/to/directory'\u001b[39;00m\n\u001b[1;32m----> 4\u001b[0m \u001b[43mos\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mchdir\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43m/path/to/directory\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n",
      "\u001b[1;31mFileNotFoundError\u001b[0m: [WinError 3] 系统找不到指定的路径。: '/path/to/directory'"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "# 更改当前工作目录到'/path/to/directory'\n",
    "os.chdir('/path/to/directory')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5afd14bb-ab48-4f32-b429-e7b2b9430c55",
   "metadata": {},
   "source": [
    "### 10. 获取当前路径\n",
    "\n",
    "- `os.getcwd()`返回当前工作目录的路径。\n",
    "- `Path.cwd()`方法同样返回当前工作目录的路径。\n",
    "\n",
    "#### 代码示例:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "5fa9d66f-4398-463b-93ea-08dc71ff7d30",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "C:\\Users\\wdcpclover\\Desktop\\python程序基础\n",
      "C:\\Users\\wdcpclover\\Desktop\\python程序基础\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "# 打印当前工作目录的路径\n",
    "print(os.getcwd())\n",
    "\n",
    "# 使用pathlib获取并打印当前工作目录的路径\n",
    "print(Path.cwd())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bcf6dc8-899e-4d47-8806-416488b6879e",
   "metadata": {},
   "source": [
    "### 11. 检测路径有效性\n",
    "\n",
    "- `os.path.exists(path)`用于检查指定路径的文件或目录是否存在。\n",
    "- `Path.exists()`方法同样用于检查路径的存在性。\n",
    "\n",
    "#### 代码示例:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "1cfa17a9-ba5b-45d0-8ad1-7868e2a74cd3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "# 检查'example.txt'文件是否存在\n",
    "print(os.path.exists('example.txt'))\n",
    "\n",
    "# 使用pathlib检查同一文件是否存在\n",
    "print(Path('example.txt').exists())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6e03639-2ec0-43ef-b99e-b25e054d1277",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
